<template>
  <div class="dropdown" ref="DropdownRef">
    <a class="btn btn-outline-light my-2 dropdown-toggle" href="#" @click.prevent="toggleOpen">
      {{title}}
    </a>
    <ul class="dropdown-menu" v-if="isOpen" :style="{display: 'block'}">
      <slot></slot>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import useClickOutside from './../hooks/useClickOutside'
export default defineComponent({
  name: 'dropdown',
  props: {
    title: {
      type: String,
      required: true
    }
  },
  setup () {
    const isOpen = ref(false)
    const toggleOpen = () => {
      isOpen.value = !isOpen.value
    }
    // DropdownRef命名必须与ref的命名一样，这样才会返回一个dom节点
    const DropdownRef = ref<null | HTMLElement>(null)
    const isClickOutside = useClickOutside(DropdownRef)
    watch(isClickOutside, () => {
      if (isOpen.value && isClickOutside.value) {
        isOpen.value = false
      }
    })
    return {
      isOpen,
      toggleOpen,
      DropdownRef
    }
  }
})
</script>
